<?php
namespace app\common\bonus;

Class Guanli extends Common
{
	static $bonus_name='guanli';

	public function handle($data){
		$actionData = $data['action_data'];

		$uid = $actionData['uid'];
		$bonus = $actionData['xiaoshou_bonus'];
		$reason_time = $actionData['reason_time'];

		$bonusConfigModel = model('bonus_config');
		// 货币配置
		$coinConfig = $bonusConfigModel::bonusConfig(self::$bonus_name,'coin');
		$coinConfig = unserialize($coinConfig['config_value']);
		// 推荐人配置
		$tuijianConfig = $bonusConfigModel::bonusConfig(self::$bonus_name,'tuijian');
		$tuijianConfig = unserialize($tuijianConfig['config_value']);
		// 将会员等级作为键名
		$tuijianConfig = array_combine(array_column($tuijianConfig,'level_id'),$tuijianConfig);
		// 封顶值配置
		$maxConfig = $bonusConfigModel::bonusConfig(self::$bonus_name,'max');
		$maxConfig = unserialize($maxConfig['config_value']);
		$maxConfig = array_combine(array_column($maxConfig,'level_id'),$maxConfig);

		//dump($tuijianConfig);die;
		$floors = [];
		foreach($tuijianConfig as $con):
			$floors[] = sizeof($con['ple_data']);
		endforeach;
		$maxFloor = max($floors); // 配置中的最大邀请层数

		// 找到产生销售补贴的用户$uid范围在$maxFloor以内的所有上级邀请人
		$inviters = model('member_inviter')->getDatas(['uid'=>$uid,'index'=>['<',$maxFloor]]);
		//dump($inviters);die;

		$memberModel = model('member');
		$memberModel -> startTrans();
		try{
			// 对每个上级邀请人计算管理补贴
			foreach($inviters as $inviter):
				// 获取该邀请人的等级
				$level_id = $memberModel->where(['id'=>$inviter['inviter_uid']])->value('level_id');
				// 获取该邀请人所在会员等级的配置
				$config = $tuijianConfig[$level_id]['ple_data'];
				// 获取该邀请人所在会员等级的封顶值
				$max_config = $maxConfig[$level_id];
				$max = $max_config['max'];
				
				// 产生销售补贴的用户是该邀请人的第多少层下线
				$floor = $inviter['floor'];
				// 该层是否存在配置中
				if(isset($config[$floor])){
					$bonus_config = $config[$floor]['config'];
					// 基于该配置计算管理补贴
					$guanli_bonus = $bonus*$bonus_config/100;
					// 比较封顶值
					$inc_result = $this->mathMax(self::$bonus_name,$inviter['inviter_uid'],$guanli_bonus,$max,$reason_time);
					$inc_bonus = $inc_result['inc_bonus'];
					$inc_tip = $inc_result['tip'];
					// 货币分配
					$this->bonus_record($coinConfig,self::$bonus_name,$uid,$inviter['inviter_uid'],$inc_bonus,$reason_time,$inc_tip);
				}else{
					continue;
				}
			endforeach;

			$memberModel->commit();
		catch(\Exception $e){
			$memberModel->rollback();
			$this->error = $e->getMessage();
			return false;
		}
		return true;

	}

}